<template>
  <section class="todoapp">
    <todo-header @add="handAdd"></todo-header>

  <todo-main :list="list2" @del="handDel" @state="handlState" @changeAllState="handlAllState"></todo-main>

  <todo-footer :flag="flag" :list="list" @clearCompleted="handlClear" @changFlag="val =>{flag = val}"></todo-footer>
  </section>
</template>

<script>
import TodoFooter from './components/TodoFooter.vue'
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
export default {
  components: { TodoHeader, TodoFooter, TodoMain },
  data(){
    return{
      list:JSON.parse(localStorage.getItem('todo-list')) || [],
      // list:[
      //   { id: 12, name: '吃饭', isDone: false },
      //   { id: 14, name: '听歌', isDone: true },
      //   { id: 23, name: '洗澡', isDone: true },
      //   { id: 34, name: '睡觉', isDone: false },
      //   { id: 35, name: '游戏', isDone: false }
      // ],
      flag:1 
    }
  },
  methods:{
    handDel(id){
      // console.log(id);
      this.list = this.list.filter(item => item.id !== id)
    },
    handAdd(todo){
      // console.log(todo);
      // this.list.push() //push 向数组末尾添加一个元素
      this.list.unshift({id:Date.now(),name:todo,isDone:false})  //unshift 向数组的开头添加元素


    },
    handlState(id){
      // console.log(id);
      const row = this.list.find(item => item.id === id)
      row.isDone = !row.isDone
    },
    // isDone=true的是已完成的清除掉已完成的，就是保留未完成的
    handlClear(){
     this.list = this.list.filter(item => item.isDone === false)
    },
    handlAllState(boo){
      this.list.forEach(item => {
        item.isDone = boo
      })
    }
  },
  computed:{
    list2(){
      if(this.flag === 2){
        return this.list.filter(item => item.isDone === false)
      }else if (this.flag ===3){
        return this.list.filter(item =>item.isDone === true )
      }else{
        return this.list
      }
      
    }
  },
  watch:{
    list:{
      handler(val){
        localStorage.setItem('todo-list',JSON.stringify(val))
      },
      // immediate:true, //立即侦听
      deep:true  //深度侦听(用于侦听对象属性的变化)
    }
  }
}
</script>

<style>

</style>
